import { App, Form, Input, Tooltip, Button } from 'antd'
import {
  type CorpDetail,
  type QywxAPIConfig,
  type AppsCorpInfo,
  type EditCorp as Values,
  saveCorp,
} from '../logics'
import getCorpIdImg from './get-corpid.png'
import getCorpIdOriginImg from './get-corpidorigin.png'
import getSecretImg from './get-secret.png'

export function EditCorp({
  corp,
  apiConfigs,
  appsCorps,
  onCancel,
  onSave,
}: {
  corp?: CorpDetail
  apiConfigs: QywxAPIConfig[]
  appsCorps: AppsCorpInfo[]
  onCancel: () => void
  onSave: (corpId: string) => void
}) {
  const { message } = App.useApp()

  const initialValues = useMemo(() => {
    if (!corp) return {} as Partial<Values>
    return {
      corpId: corp.corpId,
      secret: corp.secret,
      corpIdOrigin: corp.corpIdOrigin,
      corpName: corp.appsInfo?.corpName ?? '',
    }
  }, [corp])

  const [submitting, setSubmitting] = useState(false)
  async function submit(values: Values) {
    setSubmitting(true)
    const res = await saveCorp(values, corp?.corpId, apiConfigs, appsCorps)
    setSubmitting(false)
    if (res.success) {
      void message.success(`企业${corp ? '修改' : '添加'}成功`)
      onSave(values.corpId)
    } else {
      void message.error(res.error)
    }
  }

  return <Form labelCol={{ span: 6 }} initialValues={initialValues} onFinish={submit}>
    <main>
      <Form.Item name="corpName" label="企业名称" rules={[{ required: true }]}>
        <Input placeholder="请输入企业名称" />
      </Form.Item>
      <Form.Item
        name="corpId"
        label="企业ID（CorpID）"
        rules={[{ required: true }]}
        extra={
          <Tooltip
            title={<CorpIdGuide />}
            color="white"
            overlayStyle={{ maxWidth: '450px' }}
            placement="rightTop"
          >
            <a>如何获取 CorpId？</a>
          </Tooltip>
        }
      >
        <Input placeholder="请输入企业 ID" />
      </Form.Item>
      <Form.Item
        name="secret"
        label="Secret"
        rules={[{ required: true }]}
        extra={
          <Tooltip
            title={<SecretGuide />}
            color="white"
            overlayStyle={{ maxWidth: '700px' }}
            placement="rightTop"
          >
            <a>如何获取 Secret？</a>
          </Tooltip>
        }
      >
        <Input placeholder="请输入 Secret" />
      </Form.Item>
      <Form.Item
        name="corpIdOrigin"
        label="CorpIdOrigin"
        rules={[{ required: true }]}
        extra={
          <Tooltip
            title={<CorpIdOriginGuide />}
            color="white"
            overlayStyle={{ maxWidth: '450px' }}
            placement="rightTop"
          >
            <a>如何获取 CorpIdOrigin？</a>
          </Tooltip>
        }
      >
        <Input placeholder="请输入 CorpIdOrigin" />
      </Form.Item>
    </main>
    <footer>
      <Button onClick={onCancel}>取消</Button>
      <Button type="primary" htmlType="submit" loading={submitting}>
        保存
      </Button>
    </footer>
  </Form>
}

function CorpIdGuide() {
  return <div css={styles.guide}>
    <section>企微主体的 Corpid，通常以ww开头。</section>
    <section>
      <span>可在 </span>
      <code>企微管理后台</code> - <code>我的企业</code> – <code>企业ID</code>
      <span> 处获得</span>
    </section>
    <section>
      <span>后台网址：</span>
      <a
        href="https://work.weixin.qq.com/wework_admin/frame#profile"
        target="_blank"
        rel="noreferrer"
      >
        https://work.weixin.qq.com/wework_admin/frame#profile
      </a>
    </section>
    <a href={getCorpIdImg} target="_blank" rel="noreferrer">
      <img src={getCorpIdImg} title="点击查看大图" />
    </a>
  </div>
}
function SecretGuide() {
  return <div css={styles.guide}>
    <section>企微“客户联系”功能的 Secret。</section>
    <section>
      <span>可在 </span>
      <code>企微管理后台</code> - <code>客户与上下游</code> - <code>点开“API”小按钮</code>
      <span> 获得</span>
    </section>
    <section>
      <span>后台网址：</span>
      <a
        href="https://work.weixin.qq.com/wework_admin/frame#/customer/analysis"
        target="_blank"
        rel="noreferrer"
      >
        https://work.weixin.qq.com/wework_admin/frame#/customer/analysis
      </a>
    </section>
    <a href={getSecretImg} target="_blank" rel="noreferrer">
      <img src={getSecretImg} title="点击查看大图" />
    </a>
  </div>
}
function CorpIdOriginGuide() {
  return <div css={styles.guide}>
    <section>企微主体的原始 Corpid，通常为 1970 开头的一串数字。</section>
    <section>登录企微管理后台，右键查看网页源代码，搜索「corpid」即可获得。</section>
    <section>
      <span>后台网址：</span>
      <a href="https://work.weixin.qq.com/wework_admin/frame" target="_blank" rel="noreferrer">
        https://work.weixin.qq.com/wework_admin/frame
      </a>
    </section>
    <a href={getCorpIdOriginImg} target="_blank" rel="noreferrer">
      <img src={getCorpIdOriginImg} title="点击查看大图" />
    </a>
  </div>
}

const styles = {
  guideWrap: css`
    max-width: 500px;
  `,
  guide: css`
    color: #000;
    padding: 12px;
    font-size: 12px;
    code {
      color: #fa541c;
    }
    section {
      margin-bottom: 12px;
    }
    img {
      display: block;
      max-width: 400px;
      border-radius: 6px;
    }
  `,
}
